package com.zym.testpoi.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class DownloadUtil {

    public static void download(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
        String path = System.getProperty("java.io.tmpdir") + UUID.randomUUID() + ".xlsx";
        File file = new File(path);//在系统的临时目录生成一个excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list,true);
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("测试excel下载","UTF-8")+".xlsx");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
        // 终止后删除临时文件
        file.deleteOnExit();
    }

    public static void downloadMoreSheet(List list,List<String> sheetNameList,HttpServletResponse response) throws IOException {
        String path = System.getProperty("java.io.tmpdir") + UUID.randomUUID() + ".xlsx";
        File file = new File(path);//在系统的临时目录生成一个excel
        ExcelWriter writer = ExcelUtil.getWriter();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0){
                writer.renameSheet(0,sheetNameList.get(i));
            }else{
                writer.setSheet(sheetNameList.get(i));
            }
            writer.setSheet(sheetNameList.get(i));
            Object object = list.get(i);
            writer.write((Iterable<?>) object);
        }
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("测试excel下载","UTF-8")+".xlsx");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
        // 终止后删除临时文件
        file.deleteOnExit();
    }
}
